package com.lian.chatroom.client;

import com.lian.chatroom.message.PingMessage;
import com.lian.chatroom.protocol.MessageCodecSharable;
import com.lian.chatroom.protocol.ProtocolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ChatClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup clientEventLoop = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap
                    .group(clientEventLoop)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //自定义长度解码器，基于协议级别，解决粘包半包的处理
                            pipeline.addLast(new ProtocolFrameDecoder());
                            //日志处理器
                            //pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
                            //解码将ByteBuf数据转为字符串，编码将字符串格式转为ByteBuf格式
                            //此处是将输入的用户名密码字符串格式编码为服务器可识别的ByteBuf格式
                            pipeline.addLast(new MessageCodecSharable());
                            //添加读写空闲事件处理器
                            // 用来判断是不是 读空闲时间过长，或 写空闲时间过长
                            // 3s 内如果没有向服务器写数据，会触发一个 IdleState#WRITER_IDLE 事件
                            pipeline.addLast(new IdleStateHandler(0,3,0));
                            // ChannelDuplexHandler 可以同时作为入站和出站处理器，专门配合处理读写空闲事件
                            pipeline.addLast(new ChannelDuplexHandler(){
                                @Override
                                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                                    IdleStateEvent event = (IdleStateEvent) evt;
                                    //如果是触发的写空闲事件
                                    if (event.state() == IdleState.WRITER_IDLE){
                                        //发心跳包证明自己还活着
                                        //log.debug("3s 没有写数据了，发送一个心跳包");
                                        ctx.writeAndFlush(new PingMessage());
                                    }
                                }
                            });
                            //自定义处理器，和业务相关
                            pipeline.addLast(new ClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect("localhost", 6666).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            log.error("client error",e);
        }finally {
            clientEventLoop.shutdownGracefully();
        }
    }
}
